import React from 'react'
import './message.css'
import { Route } from 'react-router-dom'
import List from '@app/message/list'
import Detail from '@app/message/detail'

class Message extends React.Component {

  state = {
    unListen: null, // 路由监听器
  }

  componentDidMount() {
    // 监听路由事件
    this.goList(this.props.location.pathname)
    let unListen = this.props.history.listen(location => {
      this.goList(location.pathname)
    })  
    this.setState({
      unListen
    })
  }

  // 生命周期函数-组件销毁时执行
  componentWillUnmount() {
    console.log('销毁message组件路由监听')
    let { unListen } = this.state
    unListen && unListen()  
  }

  // 前往列表页
  goList = (pathname) => {
    if (pathname.indexOf('/message') !== -1 && !pathname.split('/message')[1]) {
      this.props.history.replace('/message/list')
    }
  }

  render() {
    return (
      <div className="_message">
        <Route path="/message/list" exact component={ List }></Route>
        <Route path="/message/detail" exact component={ Detail }></Route>
      </div>
    )
  }

}

export default Message